package com.own.component.util.locate.impl;

import com.own.component.util.locate.base.LocateManager;
import com.own.component.util.locate.model.LocateModel;
import com.own.component.util.locate.model.LocatePositionModel;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

/**
 * DefaultHeaderRequestLocateManager
 *
 * @author chenxueli
 * @date 2023-08-01 09:58:14
 */
public class DefaultHeaderRequestLocateManager implements LocateManager {

    private static final String LATITUDE = "latitude";
    private static final String LONGITUDE = "longitude";
    private static final String CITY = "l-city";
    private static final String COUNTY = "l-county";

    private final HttpServletRequest request;

    public DefaultHeaderRequestLocateManager(HttpServletRequest request) {
        this.request = request;
    }

    /**
     * 获取请求中的经纬度信息
     *
     * @return 经纬度信息
     */
    @Override
    public LocateModel locate() {
        var latitude = request.getHeader(LATITUDE);
        var longitude = request.getHeader(LONGITUDE);
        if (!StringUtils.hasText(latitude) || !StringUtils.hasText(longitude)) {
            return LocateModel.NONE;
        }
        return new LocateModel(latitude, longitude);
    }

    /**
     * 获取请求中的位置信息
     *
     * @return 位置信息
     */
    @Override
    public LocatePositionModel locatePosition() {
        var city = URLDecoder.decode(request.getHeader(CITY), StandardCharsets.UTF_8);
        var county = URLDecoder.decode(request.getHeader(COUNTY), StandardCharsets.UTF_8);
        return new LocatePositionModel(city, county);
    }

}
